﻿// -----------------------------------------------------------------------
// <copyright file="CrmDataAccess.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace hardvinyp.xrm
{
    using System;
    using System.Net;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Client;
    using System.ServiceModel.Description;
    using Microsoft.Crm.Sdk.Messages;

    /// <summary>
    /// Clase encargada de realizar una conexion a CRM Dynamics.
    /// </summary>
    public class CrmDataAccess
    {
        private TConexion parametroscon;

        public CrmDataAccess(TConexion ParametrosConexion)
        {
            parametroscon = ParametrosConexion;
        }

        public IOrganizationService GetOrganisationService()
        {

            ClientCredentials credentials;
            OrganizationServiceProxy service;
            try
            {
                credentials = new ClientCredentials();
                credentials.Windows.ClientCredential = new NetworkCredential(parametroscon.Usuario, parametroscon.Clave, parametroscon.Dominio);
                service = new OrganizationServiceProxy(new Uri(parametroscon.Rutaservicio), null, credentials, null);
                return service as IOrganizationService;

            }
            catch (Exception)
            {
                throw;
            }
        }

        public OrganizationResponse ExecuteorganizationRequest(OrganizationRequest or)
        {
            return GetOrganisationService().Execute(or);
        }

        public EntityCollection RetrieveMultiple(QueryExpression Consulta)
        {
            EntityCollection resultado;
            try
            {
                resultado = GetOrganisationService().RetrieveMultiple(Consulta);
                return resultado;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                resultado = null;
            }
        }
    }
}
